import csv
from py2neo import Graph, Node, Relationship
from py2neo.matching import NodeMatcher
from py2neo.data import Node, Relationship
from py2neo.ogm import GraphObject, Property, RelatedTo, RelatedFrom
import datetime
import json

# Delete all nodes and relationships
graph = Graph("bolt://localhost:7687", auth=("neo4j", "neo5j"))
graph.delete_all()

csv_file = open("movie-all-proc.csv", "r", encoding="utf-8")
csv_reader = csv.reader(csv_file, delimiter=",", quotechar='"')
next(csv_reader)
graph = Graph("bolt://localhost:7687", auth=("neo4j", "neo5j"))
matcher = NodeMatcher(graph)
for row in csv_reader:
    try:
        print(row)
        if len(row[5].split("-")) == 3:
            releaseTime = datetime.date(int(row[5].split("-")[0]), int(row[5].split("-")[1]), int(row[5].split("-")[2]))
        elif len(row[5].split("-")) == 2:
            releaseTime = datetime.date(int(row[5].split("-")[0]), int(row[5].split("-")[1]), 1)
        else:
            releaseTime = datetime.date(int(row[5].split("-")[0]), 1, 1)
        movie = Node("Movie", name=row[0], link=row[1], releaseTime=releaseTime, runTime=int(row[6]), star=float(row[7]))
        graph.create(movie)
        genres = json.loads(row[2].replace("'", '"'))
        for genre in genres:
            genre = Node("Genre", name=genre)
            graph.create(genre)
            graph.create(Relationship(movie, "属于", genre))
        director = Node("Director", name=row[3])
        graph.create(director)
        graph.create(Relationship(movie, "导演", director))
        actors = json.loads(row[4].replace("'", '"'))
        for actor in actors:
            actor = Node("Actor", name=actor)
            graph.create(actor)
            graph.create(Relationship(movie, "主演", actor))
        print("Done")
    except Exception as e:
        print("Error", e)
        pass